package com.yimi.appstore.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yimi.appstore.R;
import com.yimi.appstore.adapter.MyAdapter;
import com.yimi.appstore.adapter.MyViewPager;
import com.yimi.appstore.db.AppInfo;
import com.yimi.appstore.db.dao.AppInfoEntity;
import com.yimi.appstore.db.dao.AppInfoEntityManager;
import com.yimi.appstore.util.AppSizeUtil;
import com.yimi.appstore.util.BitmapUtil;
import com.yimi.appstore.util.FileUtils;
import com.yimi.appstore.util.SharedPrefsUtil;
import com.yimi.appstore.util.Util;

/**
 * apk管理页
 * 
 * @author Tank
 * 
 */
public class ApkExplorerActivity extends Activity implements android.widget.CompoundButton.OnCheckedChangeListener,
		OnClickListener {

	private static final String TAG = "ApkExplorerActivity";
	private Context mContext;
	private RadioGroup tab_content;
	private View cursor;
	private ViewPager awesomePager;
	private int mCurrentCheckedRadioLeft;// 当前的Tab距离左侧的距离
	private List<RadioButton> rb_pages = new ArrayList<RadioButton>();
	private List<View> listViews;
	private LayoutInflater mInflater;
	private int cursorWidth;// 宽度
	private List<String> channels = new ArrayList<String>();
	private AppInfoEntityManager appInfoEntityManager;
	private RadioButton rb1, rb2, rb3;
	private ArrayList<String> selectedPkg = new ArrayList<String>();
	public static List<AppInfo> appInstalledList = new ArrayList<AppInfo>();
	private ApkReceiver apkReceiver;

	public static void lanuchActivity(Context cx) {
		Intent i = new Intent(cx, ApkExplorerActivity.class);
		cx.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.apk_explorer_layout);
		initUI();

	}

	@Override
	protected void onStart() {
		super.onStart();
		apkReceiver = new ApkReceiver();
		IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_DATA_CLEARED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		registerReceiver(apkReceiver, filter);
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "onStop");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "onPause");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		unregisterReceiver(apkReceiver);
	}

	private void initUI() {
		mInflater = getLayoutInflater();
		appInfoEntityManager = AppInfoEntityManager.getInstance();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		cursorWidth = dm.widthPixels / 3;
		tab_content = (RadioGroup) findViewById(R.id.tab_content);
		cursor = findViewById(R.id.cursor);
		LayoutParams cursor_Params = cursor.getLayoutParams();
		cursor_Params.width = cursorWidth;// 初始化滑动下标的宽
		cursor.setLayoutParams(cursor_Params);
		initTabContent();
		initTabValue();
		initListener();
		creatViewPager();
		checkboxRl = (RelativeLayout) findViewById(R.id.checkbox_rl);
		selectedCountTv = (TextView) findViewById(R.id.selected_count_tv);
		allSelectedcb = (CheckBox) findViewById(R.id.all_check);
		unstallBtn = (Button) findViewById(R.id.unistall_apk_btn);
		cancleBtn = (Button) findViewById(R.id.cancle_checkbox_btn);
		allSelectedcb.setOnCheckedChangeListener(this);
		cancleBtn.setOnClickListener(this);
		unstallBtn.setOnClickListener(this);
	}

	// 初始化Tabcontent
	private void initTabContent() {
		channels.add("已安装");
		channels.add("可升级");
		channels.add("可移动");
		for (int i = 0; i < channels.size(); i++) {
			RadioButton radioButton = (RadioButton) mInflater.inflate(R.layout.tab_group_item, null);
			radioButton.setId(i);
			radioButton.setText(channels.get(i));
			radioButton.setLayoutParams(new LayoutParams(cursorWidth, LayoutParams.FILL_PARENT));
			if (i == 0)
				radioButton.setChecked(true);
			rb_pages.add(radioButton);

		}

	}

	private void initTabValue() {
		tab_content.removeAllViews();
		for (int i = 0; i < channels.size(); i++) {
			rb_pages.get(i).setText(channels.get(i));
			tab_content.addView(rb_pages.get(i));
		}
	}

	private void initListener() {
		findViewById(R.id.go_back_btn).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tab_content.setOnCheckedChangeListener(top_tab_onCheckedChangeListener);
	}

	private void creatViewPager() {
		if (listViews == null) {
			listViews = new ArrayList<View>();
			listViews.add(gettInstalledApp());
			listViews.add(getUpdatedApp());
			listViews.add(getMovedApp());
		}
		awesomePager = new MyViewPager(mContext, R.id.vPager, listViews).getAwesomePager();
		awesomePager.setOnPageChangeListener(new MyOnPageChangeListener());
		awesomePager.setCurrentItem(0);
		getInstalledApk();
	}

	private ExpandableListView appListview;
	// private ListView appListview;
	private InstalledExpandableAdapter appAdapter;
	// private MyAdapter appAdapter;
	private ProgressBar pbar;
	private TextView tvError;
	private boolean isLoadingInstalled;
	private RelativeLayout checkboxRl;
	private CheckBox allSelectedcb;
	private Button unstallBtn, cancleBtn;
	private TextView selectedCountTv;
	private int a_nLastItem = 0;

	/**
	 * 初始化已安装应用页面
	 * 
	 * @return
	 */
	private View gettInstalledApp() {
		View installedV = mInflater.inflate(R.layout.apk_installed_layout, null);
		appListview = (ExpandableListView) installedV.findViewById(R.id.app_list);
		pbar = (ProgressBar) installedV.findViewById(R.id.progress_bar);
		tvError = (TextView) installedV.findViewById(R.id.tv_error);
		appListview.setGroupIndicator(null);
		appListview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					BitmapUtil.updateAdapterLocalBitmap(appListview, appAdapter, AppInfoEntity.APP_PACKAGE_NAME,
							AppInfoEntity.APP_ICON, mContext);// 异步获取app图片
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				a_nLastItem = firstVisibleItem + visibleItemCount;
				appListview.setNextFocusDownId(a_nLastItem);
				appListview.setNextFocusUpId(firstVisibleItem);
			}
		});

		appListview.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {
				for (int i = 0; i < appAdapter.getGroupCount(); i++) {
					if (i != groupPosition && appListview.isGroupExpanded(groupPosition)) {
						appListview.collapseGroup(i);
					}
				}
			}
		});
		return installedV;
	}

	private List<HashMap<String, Object>> apptempList = new ArrayList<HashMap<String, Object>>();

	/**
	 * 获取已安装apk
	 */
	private void getInstalledApk() {
		if (pbar.getVisibility() == View.VISIBLE) {
			new AsyncTask<Void, Void, List<AppInfo>>() {

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					pbar.setVisibility(View.VISIBLE);
					tvError.setVisibility(View.GONE);
					appListview.setVisibility(View.GONE);
				}

				@Override
				protected List<AppInfo> doInBackground(Void... params) {
					isLoadingInstalled = true;
					appInstalledList = appInfoEntityManager.getAllApps();
					if (appInstalledList == null || appInstalledList.size() == 0) {
						appInstalledList = Util.getAppInfo(getApplicationContext());
						SharedPrefsUtil.putValue(mContext, "isIndb", false);
					}
					return appInstalledList;
				}

				@Override
				protected void onPostExecute(final List<AppInfo> result) {
					super.onPostExecute(result);
					pbar.setVisibility(View.GONE);
					isLoadingInstalled = false;
					apptempList = Util.ObjectTomap(result);
					mHandler.sendEmptyMessage(2);
					if (result != null) {
						appListview.setVisibility(View.VISIBLE);
						if (appAdapter == null) {
							appAdapter = new InstalledExpandableAdapter(mContext, apptempList);
							appListview.setAdapter(appAdapter);
							// appListview.setAdapter(new
							// SlideExpandableListAdapter(appAdapter,
							// R.id.app_installed_rl,
							// R.id.download_options_rl));
						} else {
							appAdapter.updateListData(apptempList);
						}

						BitmapUtil.updateAdapterLocalBitmap(appListview, appAdapter, AppInfoEntity.APP_PACKAGE_NAME,
								AppInfoEntity.APP_ICON, mContext);// 异步获取app图片

						if (!SharedPrefsUtil.getValue(mContext, "isIndb", false)) {
							for (HashMap<String, Object> item : apptempList) {
								appInfoEntityManager.addApp(new AppInfo(0, "" + item.get(AppInfoEntity.APP_NAME), ""
										+ item.get(AppInfoEntity.APP_PACKAGE_NAME), ""
										+ item.get(AppInfoEntity.APP_VERSION_NAME), ""
										+ item.get(AppInfoEntity.APP_VERSION_CODE), "", ((Integer) item
										.get(AppInfoEntity.APP_SIZE)),
										(Integer) item.get(AppInfoEntity.APP_TARNS_FLAG), (Integer) item
												.get(AppInfoEntity.APP_SYSTEM_FALG), null));
							}
							SharedPrefsUtil.putValue(mContext, "isIndb", true);
							Log.d(TAG, "应用入库完毕，总数：" + apptempList.size());
						}

						new AsyncTask<Void, Void, Void>() {
							@Override
							protected Void doInBackground(Void... arg0) {

								AppSizeUtil appSizeUtil = new AppSizeUtil();
								for (int i = 0; i < result.size(); ++i) {
									HashMap<String, Object> item = apptempList.get(i);
									if ((Integer) item.get(AppInfoEntity.APP_SIZE) == 0) {
										Long l = null;
										int tag = -1;
										try {
											l = appSizeUtil.queryPacakgeSize(getApplicationContext(),
													(String) item.get(AppInfoEntity.APP_PACKAGE_NAME));

											tag = appSizeUtil.queryCanMoveApk(getApplicationContext(),
													(String) item.get(AppInfoEntity.APP_PACKAGE_NAME));
											if (tag < 0) {
												item.put(AppInfoEntity.APP_TARNS_FLAG, -1);
											} else {
												item.put(AppInfoEntity.APP_TARNS_FLAG, tag);
											}

										} catch (Exception e) {
											e.printStackTrace();
										}
										item.put(AppInfoEntity.APP_SIZE, l.intValue());
										Log.d("",
												"appName:" + item.get(AppInfoEntity.APP_NAME) + ",appSize:"
														+ item.get(AppInfoEntity.APP_SIZE));
										appInfoEntityManager.updataApp(new AppInfo(0, ""
												+ item.get(AppInfoEntity.APP_NAME), ""
												+ item.get(AppInfoEntity.APP_PACKAGE_NAME), ""
												+ item.get(AppInfoEntity.APP_VERSION_NAME), ""
												+ item.get(AppInfoEntity.APP_VERSION_CODE), "", ((Integer) item
												.get(AppInfoEntity.APP_SIZE)), (Integer) item
												.get(AppInfoEntity.APP_TARNS_FLAG), (Integer) item
												.get(AppInfoEntity.APP_SYSTEM_FALG), null));
										mHandler.sendEmptyMessage(0);
									}

								}
								return null;
							}

							protected void onPostExecute(Void result) {
							};
						}.execute();
					} else {
						tvError.setVisibility(View.VISIBLE);
					}
				}

			}.execute();
		}
	}

	/**
	 * 接收消息ui刷新
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				appAdapter.notifyDataSetChanged();
				break;
			case 1:
				appMovedAdapter.notifyDataSetChanged();
				break;
			case 2:
				rb_pages.get(0).setText("已安装(" + appInstalledList.size() + ")");
				break;
			case 3:
				rb_pages.get(2).setText("可移动(" + canMovedAppList.size() + ")");
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 获取可升级应用的view
	 * 
	 * @return
	 */
	private View getUpdatedApp() {
		TextView tv = new TextView(mContext);
		tv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		tv.setText("可升级");
		return tv;
	}

	/**
	 * 获取可移动应用
	 * 
	 * @return
	 */

	private ExpandableListView appMovedListview;
	private InstalledExpandableAdapter appMovedAdapter;
	private ProgressBar appMovedpbar;
	private TextView tvappMovedError;
	private boolean isLoadingMoved;
	private List<HashMap<String, Object>> canMovedAppList = new ArrayList<HashMap<String, Object>>();
	private List<HashMap<String, Object>> canMoveapptempList = new ArrayList<HashMap<String, Object>>();
	private HashMap<String, Object> selectedAppitem;
	private int m_nLastItem;
	/**
	 * 获取可移动应用的view
	 * 
	 * @return
	 */
	private View getMovedApp() {
		View appMovedV = mInflater.inflate(R.layout.apk_installed_layout, null);
		appMovedListview = (ExpandableListView) appMovedV.findViewById(R.id.app_list);
		appMovedpbar = (ProgressBar) appMovedV.findViewById(R.id.progress_bar);
		tvappMovedError = (TextView) appMovedV.findViewById(R.id.tv_error);
		appMovedListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				selectedAppitem = (HashMap<String, Object>) arg0.getAdapter().getItem(arg2);
				Util.showInstalledAppDetails(mContext,
						(String) selectedAppitem.get(AppInfoEntity.APP_PACKAGE_NAME));

			}
		});
		
		appMovedListview.setGroupIndicator(null);
		appMovedListview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					BitmapUtil.updateAdapterLocalBitmap(appMovedListview, appMovedAdapter, AppInfoEntity.APP_PACKAGE_NAME,
							AppInfoEntity.APP_ICON, mContext);// 异步获取app图片
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				m_nLastItem = firstVisibleItem + visibleItemCount;
				appMovedListview.setNextFocusDownId(m_nLastItem);
				appMovedListview.setNextFocusUpId(firstVisibleItem);
			}
		});

		appMovedListview.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {
				for (int i = 0; i < appMovedAdapter.getGroupCount(); i++) {
					if (i != groupPosition && appMovedListview.isGroupExpanded(groupPosition)) {
						appMovedListview.collapseGroup(i);
					}
				}
			}
		});		
		return appMovedV;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume() 移动到sdk后刷新list
	 */
	@Override
	protected void onResume() {
		super.onResume();
		AppSizeUtil appSizeUtil = new AppSizeUtil();
		int tag = 0;
		try {
			tag = appSizeUtil.queryCanMoveApk(getApplicationContext(),
					(String) selectedAppitem.get(AppInfoEntity.APP_PACKAGE_NAME));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (tag == 1) {
			canMovedAppList.remove(selectedAppitem);
			appInfoEntityManager.updataAppTransflg((String) selectedAppitem.get(AppInfoEntity.APP_PACKAGE_NAME), tag);
			appMovedAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 获取可移动apk
	 */
	private void getMovedApk() {
		if (appMovedpbar.getVisibility() == View.VISIBLE) {
			new AsyncTask<Void, Void, List<AppInfo>>() {

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					appMovedpbar.setVisibility(View.VISIBLE);
					tvappMovedError.setVisibility(View.GONE);
					appMovedListview.setVisibility(View.GONE);
				}

				@Override
				protected List<AppInfo> doInBackground(Void... params) {
					isLoadingMoved = true;
					appInstalledList = appInfoEntityManager.getAllApps();
					if (appInstalledList == null || appInstalledList.size() == 0) {
						appInstalledList = Util.getAppInfo(getApplicationContext());
						SharedPrefsUtil.putValue(mContext, "isIndb", false);

					}
					return appInstalledList;
				}

				@Override
				protected void onPostExecute(final List<AppInfo> result) {
					super.onPostExecute(result);
					if (result != null) {
						canMoveapptempList = Util.ObjectTomap(result);
						if (!SharedPrefsUtil.getValue(mContext, "isIndb", false)) {
							for (HashMap<String, Object> item : canMoveapptempList) {
								appInfoEntityManager.addApp(new AppInfo(0, "" + item.get(AppInfoEntity.APP_NAME), ""
										+ item.get(AppInfoEntity.APP_PACKAGE_NAME), ""
										+ item.get(AppInfoEntity.APP_VERSION_NAME), ""
										+ item.get(AppInfoEntity.APP_VERSION_CODE), "", ((Integer) item
										.get(AppInfoEntity.APP_SIZE)),
										(Integer) item.get(AppInfoEntity.APP_TARNS_FLAG), (Integer) item
												.get(AppInfoEntity.APP_SYSTEM_FALG), (Drawable) item
												.get(AppInfoEntity.APP_ICON)));
							}
							SharedPrefsUtil.putValue(mContext, "isIndb", true);
							Log.d(TAG, "应用入库完毕，总数：" + canMoveapptempList.size());
						}

						new AsyncTask<Void, Void, Void>() {
							@Override
							protected Void doInBackground(Void... arg0) {

								AppSizeUtil appSizeUtil = new AppSizeUtil();
								for (int i = 0; i < result.size(); ++i) {
									HashMap<String, Object> item = canMoveapptempList.get(i);
									if ((Integer) item.get(AppInfoEntity.APP_SIZE) == 0) {
										Long l = null;
										int tag = -1;
										try {
											l = appSizeUtil.queryPacakgeSize(getApplicationContext(),
													(String) item.get(AppInfoEntity.APP_PACKAGE_NAME));

											tag = appSizeUtil.queryCanMoveApk(getApplicationContext(),
													(String) item.get(AppInfoEntity.APP_PACKAGE_NAME));
											if (tag < 0) {
												item.put(AppInfoEntity.APP_TARNS_FLAG, -1);
											} else {
												item.put(AppInfoEntity.APP_TARNS_FLAG, tag);
											}

										} catch (Exception e) {
											e.printStackTrace();
										}
										item.put(AppInfoEntity.APP_SIZE, l.intValue());
										Log.d("",
												"appName:" + item.get(AppInfoEntity.APP_NAME) + ",appSize:"
														+ item.get(AppInfoEntity.APP_SIZE));
										appInfoEntityManager.updataApp(new AppInfo(0, ""
												+ item.get(AppInfoEntity.APP_NAME), ""
												+ item.get(AppInfoEntity.APP_PACKAGE_NAME), ""
												+ item.get(AppInfoEntity.APP_VERSION_NAME), ""
												+ item.get(AppInfoEntity.APP_VERSION_CODE), "", ((Integer) item
												.get(AppInfoEntity.APP_SIZE)), (Integer) item
												.get(AppInfoEntity.APP_TARNS_FLAG), (Integer) item
												.get(AppInfoEntity.APP_SYSTEM_FALG), (Drawable) item
												.get(AppInfoEntity.APP_ICON)));
									}

								}
								canMovedAppList = Util.ObjectTomap(appInfoEntityManager.getAllMovedApps());
								mHandler.sendEmptyMessage(3);
//								new AsyncTask<Void, Void, Void>() {
//
//									@Override
//									protected Void doInBackground(Void... params) {
//										for (int i = 0; i < canMovedAppList.size(); i++) {
//											HashMap<String, Object> item = canMovedAppList.get(i);
//											Drawable d = Util.getBitmapBypn(
//													(String) item.get(AppInfoEntity.APP_PACKAGE_NAME), mContext);
//											item.put(AppInfoEntity.APP_ICON, d);
//											mHandler.sendEmptyMessage(1);
//										}
//										return null;
//									}
//
//								}.execute();
								return null;
							}

							protected void onPostExecute(Void result) {
								appMovedListview.setVisibility(View.VISIBLE);
								appMovedpbar.setVisibility(View.GONE);
								isLoadingMoved = false;
								if (appMovedAdapter == null) {
									appMovedAdapter = new InstalledExpandableAdapter(mContext, canMovedAppList);
									appMovedListview.setAdapter(appMovedAdapter);
								} else {
									appMovedAdapter.updateListData(canMovedAppList);
								}
								
								BitmapUtil.updateAdapterLocalBitmap(appMovedListview, appMovedAdapter, AppInfoEntity.APP_PACKAGE_NAME,
										AppInfoEntity.APP_ICON, mContext);// 异步获取app图片
							};
						}.execute();

					} else {
						tvError.setVisibility(View.VISIBLE);
					}
				}

			}.execute();
		}
	}

	/**
	 * 页卡切换监听
	 * 
	 * @author Tank
	 * 
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageSelected(int position) {
			if (tab_content != null && tab_content.getChildCount() > position) {
				tab_content.getChildAt(position).performClick();
			}
			switch (position) {
			case 0:
				if (!isLoadingInstalled)
					getInstalledApk();
				break;

			case 1:
				break;
			case 2:
				if (!isLoadingMoved)
					getMovedApk();

				break;
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	/**
	 * 顶部RadioGroup点击CheckedChanged监听
	 */
	private OnCheckedChangeListener top_tab_onCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			try {
				if (tab_content != null && tab_content.getChildCount() > 0 && tab_content.getChildAt(checkedId) != null) {
					TranslateAnimation _TranslateAnimation = new TranslateAnimation(mCurrentCheckedRadioLeft,
							((RadioButton) tab_content.getChildAt(checkedId)).getLeft(), 0f, 0f);
					// 匀速
					_TranslateAnimation.setInterpolator(new LinearInterpolator());
					_TranslateAnimation.setDuration(100);
					// 动画执行后，控件将停留在动画结束的状态
					_TranslateAnimation.setFillAfter(true);
					cursor.startAnimation(_TranslateAnimation);
					awesomePager.setCurrentItem(checkedId);// 让下方ViewPager跟随上面的HorizontalScrollView切换
					mCurrentCheckedRadioLeft = ((RadioButton) tab_content.getChildAt(checkedId)).getLeft();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	};

	/**
	 * 广播接收apk卸载
	 * 
	 * @author Tank
	 * 
	 */
	class ApkReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {

			} else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
				String packageName = intent.getDataString().substring(8);
				for (HashMap<String, Object> info : apptempList) {
					if (info.get(AppInfoEntity.APP_PACKAGE_NAME).equals(packageName)) {
						apptempList.remove(info);
						appAdapter.updateListData(apptempList);
						break;
					}
				}
				rb_pages.get(0).setText("已安装(" + apptempList.size() + ")");
			}
		}

	}

	/**
	 * 已安装apk适配器
	 * 
	 * @author Tank
	 * 
	 */
	public class AppInstalledAdapter extends MyAdapter {

		public AppInstalledAdapter(Context context, List<HashMap<String, Object>> listData) {
			super(context, listData);
		}

		class ViewHolder implements OnClickListener {
			ImageView app_icon;
			ImageView app_checkbox;
			TextView app_name, app_version, app_size, app_uninstall;
			int position = -1;
			boolean isSelected = true;

			@Override
			public void onClick(View v) {
				if (position != -1) {
					final HashMap<String, Object> item = listData.get(position);
					String pkg = (String) item.get(AppInfoEntity.APP_PACKAGE_NAME);
					if (isSelected) {
						selectedPkg.add(pkg);
						app_checkbox.setImageResource(R.drawable.btn_check_on_holo_light);
					} else if (selectedPkg.contains(pkg)) {
						selectedPkg.remove(pkg);
						app_checkbox.setImageResource(R.drawable.btn_check_off_holo_light);
					}
					item.put("select", isSelected);
					isSelected = !isSelected;
					selectedCountTv.setText("已选择" + selectedPkg.size() + "个应用");
					showToparea();
				}
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final HashMap<String, Object> item = listData.get(position);
			View v = showLoadingItem(item);
			if (v != null)
				return v;
			v = convertView;
			ViewHolder vh = null;
			if (v == null || v.getTag() == null) {
				v = lInflater.inflate(R.layout.apk_installed_item, null);
				vh = new ViewHolder();
				vh.app_checkbox = (ImageView) v.findViewById(R.id.ck_selected);
				vh.app_icon = (ImageView) v.findViewById(R.id.iv_icon);
				vh.app_name = (TextView) v.findViewById(R.id.tv_name);
				vh.app_version = (TextView) v.findViewById(R.id.tv_version);
				vh.app_size = (TextView) v.findViewById(R.id.tv_size);
				vh.app_uninstall = (TextView) v.findViewById(R.id.tv_unistall);
				v.setTag(vh);
			} else {
				vh = (ViewHolder) v.getTag();
			}
			vh.position = position;
			if (item.containsKey(AppInfoEntity.APP_ICON) && item.get(AppInfoEntity.APP_ICON) != null) {
				vh.app_icon.setImageDrawable((Drawable) item.get(AppInfoEntity.APP_ICON));
			} else {
				vh.app_icon.setImageResource(R.drawable.app_deafault);
			}
			if (item.containsKey(AppInfoEntity.APP_NAME))
				vh.app_name.setText((String) item.get(AppInfoEntity.APP_NAME));
			if (item.containsKey(AppInfoEntity.APP_VERSION_NAME))
				vh.app_version.setText("版本:" + (String) item.get(AppInfoEntity.APP_VERSION_NAME));
			if ((Integer) item.get(AppInfoEntity.APP_SIZE) != 0) {
				vh.app_size.setText(FileUtils.convertStorage((Integer) item.get(AppInfoEntity.APP_SIZE)));
			} else {
				vh.app_size.setText("正在计算");
			}
			vh.app_uninstall.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Util.unstallApk(context, (String) item.get(AppInfoEntity.APP_PACKAGE_NAME));
				}
			});
			if ((Boolean) item.get("select"))
				vh.app_checkbox.setImageResource(R.drawable.btn_check_on_holo_light);
			else
				vh.app_checkbox.setImageResource(R.drawable.btn_check_off_holo_light);
			vh.app_checkbox.setOnClickListener(vh);
			return v;
		}

	}

	public class InstalledExpandableAdapter extends BaseExpandableListAdapter {

		protected Context context;
		protected List<HashMap<String, Object>> listData;
		protected LayoutInflater lInflater;

		public InstalledExpandableAdapter(Context context, List<HashMap<String, Object>> listData) {
			this.context = context;
			this.listData = listData;
			this.lInflater = LayoutInflater.from(context);
		}

		/**
		 * 更新适配器数据
		 * 
		 * @param listData
		 */
		public void updateListData(List<HashMap<String, Object>> listData) {
			this.listData = listData;
			this.notifyDataSetChanged();
		}

		/**
		 * 获取适配器数据
		 * 
		 * @return
		 */
		public List<HashMap<String, Object>> getListData() {
			return this.listData;
		}

		class ViewHolder implements OnClickListener {
			ImageView app_icon;
			ImageView app_checkbox;
			TextView app_name, app_version, app_size, app_uninstall;
			int position = -1;
			boolean isSelected = true;

			@Override
			public void onClick(View v) {
				if (position != -1) {
					final HashMap<String, Object> item = listData.get(position);
					String pkg = (String) item.get(AppInfoEntity.APP_PACKAGE_NAME);
					if (isSelected) {
						selectedPkg.add(pkg);
						app_checkbox.setImageResource(R.drawable.mzw_settings_check);
					} else if (selectedPkg.contains(pkg)) {
						selectedPkg.remove(pkg);
						app_checkbox.setImageResource(R.drawable.mzw_settings_uncheck);
					}
					item.put("select", isSelected);
					isSelected = !isSelected;
					selectedCountTv.setText("已选择" + selectedPkg.size() + "个应用");
					showToparea();
				}
			}
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return null;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
				ViewGroup parent) {
			return getGenericView();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return listData.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return listData.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			final HashMap<String, Object> item = listData.get(groupPosition);
			View v = convertView;
			ViewHolder vh = null;
			if (v == null || v.getTag() == null) {
				v = lInflater.inflate(R.layout.apk_installed_item, null);
				vh = new ViewHolder();
				vh.app_checkbox = (ImageView) v.findViewById(R.id.ck_selected);
				vh.app_icon = (ImageView) v.findViewById(R.id.iv_icon);
				vh.app_name = (TextView) v.findViewById(R.id.tv_name);
				vh.app_version = (TextView) v.findViewById(R.id.tv_version);
				vh.app_size = (TextView) v.findViewById(R.id.tv_size);
				vh.app_uninstall = (TextView) v.findViewById(R.id.tv_unistall);
				v.setTag(vh);
			} else {
				vh = (ViewHolder) v.getTag();
			}
			vh.position = groupPosition;
			if (item.containsKey(AppInfoEntity.APP_ICON) && item.get(AppInfoEntity.APP_ICON) != null) {
				vh.app_icon.setImageDrawable((Drawable) item.get(AppInfoEntity.APP_ICON));
			} else {
				vh.app_icon.setImageResource(R.drawable.app_deafault);
			}
			if (item.containsKey(AppInfoEntity.APP_NAME))
				vh.app_name.setText((String) item.get(AppInfoEntity.APP_NAME));
			if (item.containsKey(AppInfoEntity.APP_VERSION_NAME))
				vh.app_version.setText("版本:" + (String) item.get(AppInfoEntity.APP_VERSION_NAME));
			if ((Integer) item.get(AppInfoEntity.APP_SIZE) != 0) {
				vh.app_size.setText(FileUtils.convertStorage((Integer) item.get(AppInfoEntity.APP_SIZE)));
			} else {
				vh.app_size.setText("正在计算");
			}
			vh.app_uninstall.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Util.unstallApk(context, (String) item.get(AppInfoEntity.APP_PACKAGE_NAME));
				}
			});
			if ((Boolean) item.get("select"))
				vh.app_checkbox.setImageResource(R.drawable.mzw_settings_check);
			else
				vh.app_checkbox.setImageResource(R.drawable.mzw_settings_uncheck);
			vh.app_checkbox.setOnClickListener(vh);
			return v;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		public View getGenericView() {
			View view = lInflater.inflate(R.layout.apk_installed_bottom_layout, null);
			return view;
		}

	}

	/**
	 * 显示顶部area
	 */
	private void showToparea() {
		if (!selectedPkg.isEmpty() && checkboxRl.getVisibility() != View.VISIBLE) {
			checkboxRl.setVisibility(View.VISIBLE);
		} else if (selectedPkg.isEmpty() && checkboxRl.getVisibility() == View.VISIBLE) {
			checkboxRl.setVisibility(View.GONE);
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			selectedPkg.clear();
			for (HashMap<String, Object> map : apptempList) {
				String pkg = (String) map.get(AppInfoEntity.APP_PACKAGE_NAME);
				map.put("select", true);
				selectedPkg.add(pkg);
			}
		} else {
			for (HashMap<String, Object> map : apptempList)
				map.put("select", false);
			selectedPkg.clear();
			checkboxRl.setVisibility(View.GONE);
		}
		appAdapter.updateListData(apptempList);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cancle_checkbox_btn:
			checkboxRl.setVisibility(View.GONE);
			selectedPkg.clear();
			for (HashMap<String, Object> map : apptempList)
				map.put("select", false);
			appAdapter.updateListData(apptempList);
			break;

		case R.id.unistall_apk_btn:
			checkboxRl.setVisibility(View.GONE);
			Util.unstallApks(mContext, selectedPkg);
			selectedPkg.clear();
			for (HashMap<String, Object> map : apptempList)
				map.put("select", false);
			appAdapter.updateListData(apptempList);
			break;
		}
	}

}
